package com.itcast.activiti.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.time.LocalDateTime;

/**
 * SpringBoot集成MyBatis-Plus工具类
 */
@EnableTransactionManagement
@Configuration
@MapperScan("com.itcast.**.mapper*")
public class MybatisPlusConfig implements MetaObjectHandler {

    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
        page.setOverflow(true);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        page.setLimit(-1);
        // 开启 count 的 join 优化,只针对部分 left join
        page.setCountSqlParser(new JsqlParserCountOptimize(true));
        return page;
    }

    /**
     * mybatis-plus乐观锁插件
     * 场景：当要更新一条记录的时候，希望这条记录没有被别人更新
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        //  @TableField(fill = FieldFill.INSERT)
        this.strictInsertFill(metaObject, "tenantId", Integer.class, getTenantId());
        this.strictInsertFill(metaObject, "createdDatetime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "modifiedDatetime", LocalDateTime.class, LocalDateTime.now());
    }

    static Integer getTenantId() {
        return 1;
    }
}
